package userlogic

import (
	"context"
	"time"

	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/model"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/dao/schema"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/login-rpc/login_rpc"
	config "gitee.com/liuxuezhan/ar-platform/login-rpc/pkg/code"
	"github.com/zeromicro/go-zero/core/logc"

	"github.com/zeromicro/go-zero/core/logx"
)

type HeartbeatLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewHeartbeatLogic(ctx context.Context, svcCtx *svc.ServiceContext) *HeartbeatLogic {
	return &HeartbeatLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *HeartbeatLogic) Heartbeat(in *login_rpc.HeartbeatRequest) (*login_rpc.HeartbeatResponse, error) {
	var commonResp login_rpc.CommonResp
	now := time.Now().Unix()
	var user schema.User
	user.Id = in.UserId
	user.LastOnlineTime = now
	user.IsOnline = 1
	err := model.NewUserModel(l.ctx, l.svcCtx.Db).UpdateLastOnlineTime(user)
	if err != nil {
		commonResp.Code = config.DBError
		commonResp.Message = "failed to update user's online status"
		return &login_rpc.HeartbeatResponse{CommonResp: &commonResp}, nil
	}

	// 添加登录日志
	userLoginToken := buildLoginLog(in.UserId, in.LoginInfo)
	if err = model.NewUserLoginLogsModel(l.ctx, l.svcCtx.Db).InsertUserLoginLogs(&userLoginToken); err != nil {
		logc.Infof(l.ctx, "Heartbeat: add login log failed: %v", err)
	}

	return &login_rpc.HeartbeatResponse{CommonResp: &commonResp}, nil
}
